﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class OpenPlayProjectList : System.Web.UI.Page
{
    Data.VarParams varParams;
    Data.DataConsolidation dc;
    Data.MyListString projectItems;
    Data.Data analysisProject;

    protected void Page_Load(object sender, EventArgs e)
    {
        try {
            String myDataDir = (String)Session["MyApplicationDirectory"];
            if (myDataDir == null)
            {
                myDataDir = Request.Params["a"];
                if (myDataDir == null)
                    Response.Write(" Your session is expired or this page wasn't started correctly. Try starting it with ?a=windmill for our demo data.");
            }

            // this is to be a drive/subdir where variables.config and license.config reside
            String myApplicationDir = Request.PhysicalApplicationPath + myDataDir;
            String sessionId = Session.SessionID;
            String errMsg = InitData( myApplicationDir, sessionId);
            if (errMsg != null)
            {
                Response.Write(errMsg);
                Response.Write(" Your session might have expired");
            }
            else
            {
                String projectFileName = (String)Request["projectFileName"];
                if( projectFileName != null )
                {
                    RunProjectFileToHtml( Response, projectFileName );
                }
                else
                {
                    RunAllProjectFilesToHtml( Response );
                }
            }

        } catch( Exception )
        {
        }
    }

    public void RunAllProjectFilesToHtml( HttpResponse response )
    {
        Data.MyListString filelist = Data.MyDirectory.GetFiles( varParams.GetMyProjectsDir() );

        for( int projectIndex = 0,  projectCount = filelist.GetCount() ;
                projectIndex < projectCount ; projectIndex++ )
        {
            String projectFileName = filelist.Get( projectIndex );
            if( projectFileName.StartsWith( "_" ) == false )
            {
                RunProjectFileToHtml(response, projectFileName);
            }
        }
    }

    private void RunProjectFileToHtml( HttpResponse response, String projectFileName )
    {
        String error = LoadProjectFromProjectFile( projectFileName );
        if( error != null )
            response.Write( "There was a problem building this project. " + error );
        
        else
        {
            error = ExecuteProjectLines();
            if( error != null )
                response.Write( error );
            else
                OutputHtml.RunExecutedProjectToHtml(response, projectFileName, analysisProject);
        }
    }

    private void RunScriptCommandsToHtml( HttpResponse response, String [] scriptCommands )
    {
        projectItems = new Data.MyListString( scriptCommands );
        String error = ExecuteProjectLines();
        if( error != null )
            response.Write( error );
        else
            OutputHtml.RunExecutedProjectToHtml(response, null, analysisProject);
    }
    
    public String LoadProjectFromProjectFile( String projectFileName )
    {
        if( projectFileName == null || projectFileName.Length == 0 )
        {
            return "Invalid project filename";
        }
        
        String fullProjectFileName = varParams.GetMyProjectsDir() + projectFileName;
        if( Data.MyFile.Exists( fullProjectFileName ) == false )
        {
            return fullProjectFileName + " not found";
        } 
        
        projectItems = Data.MyFile.ReadAllLines( varParams, fullProjectFileName );
        if( projectItems == null || projectItems.GetCount() == 0 )
            return "problem with contents of " + fullProjectFileName;
        else
            return null;
    }

    private String ExecuteProjectLines()
    {
        analysisProject = new Data.Data();
        if( analysisProject == null )
            return "Failed to load, probably low memory or corrupted files" ;

        for( int i=0, count = projectItems.GetCount() ; i < count ; i++ )
        {
            String scriptItem = projectItems.Get( i );
            String message = ExecuteLine( scriptItem ) ;
            if( message != null )
                return "Line " + i.ToString() + message ;
        }
        return null;    // a return value of null means success 
    }
    
    private String ExecuteLine( String scriptItem )
    {
        Boolean success = dc.RunScript( scriptItem, analysisProject, true );
        if( success == false )
            return " failed: " + scriptItem;
        else
            return null;
    }

    public String InitData( String variablesPath, String sessionId )
    {
        varParams = new Data.VarParams();
        if( varParams == null )
            return "Failed to load, probably low memory or corrupted files" ;

        String errMsg = varParams.ReadFile( variablesPath, sessionId );
        if( errMsg != null )
            return errMsg;

        dc = new Data.DataConsolidation( varParams );

        return null;
    }

}
